package com.ctgu.juc_project.test;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Map2String {
    public static void main(String[] args) throws InterruptedException {
        int mapSize = 10;
        Map<String, String> map = new HashMap<String, String>() {{
            for (int i = 0; i < mapSize; i++) {
                put("key" + i, "value" + i);
            }
        }};
        ExecutorService executorService = Executors.newFixedThreadPool(map.size());
        CountDownLatch countDownLatch = new CountDownLatch(map.size());
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        Lock writeLock = lock.writeLock();
        StringBuffer stringBuffer = new StringBuffer();
        for (Entry<String, String> entry : map.entrySet()) {
            executorService.execute(() -> {
                writeLock.lock();
                try {
                    stringBuffer.append(entry.getKey());
                    stringBuffer.append(":");
                    stringBuffer.append(entry.getValue());
                    countDownLatch.countDown();
                    if (countDownLatch.getCount() != 0) {
                        stringBuffer.append(";");
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                } finally {
                    writeLock.unlock();
                }
            });
        }
        countDownLatch.await();
        System.out.println(stringBuffer);
        executorService.shutdown();
    }
}
